package com.warningrc.system.struts.mapper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.RequestUtils;

import com.warningrc.system.Constants;

public class RestOperations {
	private List<Pattern> urlPatterns;

	public void setUrlPatterns(String urlPatterns) {
		if (this.urlPatterns == null) {
			if (null != urlPatterns && urlPatterns.trim().length() != 0) {
				List<Pattern> list = new ArrayList<Pattern>();
				String[] tokens = urlPatterns.split(",");
				for (String token : tokens) {
					list.add(Pattern.compile(token.trim()));
				}
				this.urlPatterns = Collections.unmodifiableList(list);
			}
		}
	}

	public boolean isRestUrl(HttpServletRequest request) {
		if (this.urlPatterns == null)
			return true;
		else {
			String uri = getUri(request);
			for (Pattern pattern : urlPatterns) {
				System.out.println(uri);
				if (pattern.matcher(uri).matches()) {
					return true;
				}
			}
		}
		return false;
	}

	public boolean isGet(HttpServletRequest request) {
		return !isPut(request) && !isDelete(request)
				&& "GET".equalsIgnoreCase(request.getMethod());
	}

	public boolean isPost(HttpServletRequest request) {
		return !isPut(request) && !isDelete(request)
				&& "POST".equalsIgnoreCase(request.getMethod());
	}

	public boolean isPut(HttpServletRequest request) {
		return "PUT".equalsIgnoreCase(request.getMethod())
				|| "PUT".equalsIgnoreCase(request
						.getParameter(Constants.HTTP_METHOD_PARAM));
	}

	public boolean isDelete(HttpServletRequest request) {
		return "DELETE".equalsIgnoreCase(request.getMethod())
				|| "DELETE".equalsIgnoreCase(request
						.getParameter(Constants.HTTP_METHOD_PARAM));
	}

	private String getUri(HttpServletRequest request) {
		String uri = (String) request
				.getAttribute("javax.servlet.include.servlet_path");
		if (uri != null)
			return uri;
		uri = RequestUtils.getServletPath(request);
		if (uri != null && !"".equals(uri))
			return uri;
		uri = request.getRequestURI();
		return uri.substring(request.getContextPath().length());
	}

	public static void main(String[] args) {
		String str = "/";
		Pattern pattern=Pattern.compile(str);
		System.out.println(pattern.split("/user//").length);
		System.out.println("/user//".split("/").length);
	}
}